<?php 
namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class SettingsModel extends Model
{
    const STATUS_ACTIVE = 1;
    const STATUS_DELETED = 0;

    protected $connection = 'db_main';

    protected $isSharding = 1;

    protected $table = 'wp_sdk_settings';

    protected $fillable = ['appid', 'item_key', 'item_value', 'status', 'create_time', 'modify_time'];

    public $timestamps = false;

    /**
     * 获取配置项
     */
    public static function getItemValue(){}

    /**
     * 单独存储项目下线时间、下线时间
     * @param $appid
     * @param $item_key
     * @param $item_value
     * @return array
     */
    public static function offInfoToDataBase($appid, $item_key, $item_value) {
        $baseinfo = self::where(['appid'=>$appid, 'item_key'=>$item_key, 'status'=>1])->first();
        if($baseinfo){
            $res = self::where(['appid'=>$appid, 'item_key'=>$item_key, 'status'=>1])->update(['item_key'=>$item_key, 'item_value'=>$item_value, 'modify_time'=>time()]);
        }else{
            $res = self::create([
                'appid'       => $appid,
                'item_key'    => $item_key,
                'item_value'  => $item_value,
                'status'      => 1,
                'create_time' => time(),
                'modify_time' => 0
            ]);
        }

        if ( !$res ){
            return array('code'=>1, 'msg'=>'操作失败', 'data'=>array() );
        }
        return array('code'=>0, 'msg'=>'', 'data'=>$item_value );
    }

    /**
     * 发布时将所有信息同步映射到数据库中
     * @params
     */
    public static function mapToDataBase ( $appid, $info) {
        $item = self::where(['appid'=>$appid, 'item_key'=>'baseinfo', 'status'=>self::STATUS_ACTIVE])->first();
        if($item){
            $baseinfo = json_decode($item->item_value, true);
            $info = is_array($info) ? $info : $info->toArray();
            $baseinfo = is_array($baseinfo) ? array_merge($baseinfo, $info) : $info;

            $fields['item_value'] = json_encode($baseinfo);
            $fields['modify_time'] = time();

            $res = self::where(['id'=>$item->id])->update($fields);
        }else{
            $res = self::create([
                'appid'         => $appid,
                'item_key'      => 'baseinfo',
                'item_value'    => json_encode($info),
                'status'        => 1,
                'create_time'   => time(),
                'modify_time'   => 0
            ]);

        }

        if (!$res) return ['code'=>1, 'msg'=>'映射到数据库失败', 'data'=>array()];

        return ['code'=>0, 'msg'=>'', 'data'=>$info];
    }

}